/* Copyright (c) 2010, David Kreuter. See LICENSE for more information */

#include "headers.h"

int export_map(map *m, char *path){
	export_bmd(m->b,path);
}

int export_btx(btx *x, char *path){

}

int export_bmd(bmd *b, char *_path){
	char path[200];
	char *basename=_path;
	while(*basename!=0)basename++;
	while(*basename!='/'&&*basename!='\\')basename--;
	*basename++=0;

	sprintf(path,"%s/%s.obj",_path,basename);
	FILE *f=fopen(path,"w");

	mdl *m=b->m;
	fprintf(f,"# This model was exported by \"poke-tools\"\n");
	fprintf(f,"# http://code.google.com/p/poke-tools/\n");
	fprintf(f,"\n# Name '%s'\n# %4d tris\n# %4d quads\n\nmtllib %s.mtl\n\n",
		m->name,m->num_tris,m->num_quads,basename);

	uint32 c=1;
	for(int a=0;a<m->num_layers;a++){
		mdl_layer *l=&m->layer[a];

		mdl_mat *mt=m->mat+l->mat_id;
		mdl_tex *t=m->tex+mt->tex_id;
		mdl_pal *p=m->pal+mt->pal_id;
		uint16 w=1,h=1;
		if(b->t){
			w=b->t->tex[mt->tex_id].w*WRF(mt->repeat);
			h=b->t->tex[mt->tex_id].h*HRF(mt->repeat);
			fprintf(f,"usemtl %s-%s\n",t->name,p->name);
		}else{
			fprintf(f,"usemtl none\n",t->name,p->name);
		}

		for(int b=0;b<l->num_tris;b++){
			mdl_vert *t=m->tri[b+l->tri_offset];
			for(int c=0;c<3;c++){
				fprintf(f,"v %f %f %f\n",
					t[c].pos[0],t[c].pos[1],t[c].pos[2]);
				fprintf(f,"vt %f %f\n",
					t[c].uv[0]/w,t[c].uv[1]/h);
				//fprintf(f,"col %f %f %f\n"
				//	,t[c].col[0],t[c].col[1],t[c].col[2]);
				// obj doesn't support vertex-colors
			}
			fprintf(f,"f %d/%d %d/%d %d/%d\n",
				c,c,c+1,c+1,c+2,c+2);
			c+=3;
		}
		for(int b=0;b<l->num_quads;b++){
			mdl_vert *t=m->quad[b+l->quad_offset];
			for(int c=0;c<4;c++){
				fprintf(f,"v %f %f %f\n",
					t[c].pos[0],t[c].pos[1],t[c].pos[2]);
				fprintf(f,"vt %f %f\n",
					t[c].uv[0]/w,t[c].uv[1]/h);
			}
			fprintf(f,"f %d/%d %d/%d %d/%d %d/%d\n",
				c,c,c+1,c+1,c+2,c+2,c+3,c+3);
			c+=4;
		}
	}

	fclose(f);

	if(b->t){
		sprintf(path,"%s/%s.mtl",_path,basename);
		f=fopen(path,"w");
		for(uint32 mid=0;mid<m->num_mats;mid++){
			mdl_mat *mt=m->mat+mid;
			mdl_tex *t=m->tex+mt->tex_id;
			mdl_pal *p=m->pal+mt->pal_id;
			uint16 w=b->t->tex[mt->tex_id].w*WRF(mt->repeat);
			uint16 h=b->t->tex[mt->tex_id].h*HRF(mt->repeat);
			fprintf(f,"newmtl %s-%s\n",t->name,p->name);
			fprintf(f,"\tmap_Kd %s/%s-%s.tga\n",
				_path,t->name,p->name);

			rgba *pixel=make_mat(mt->tex_id,mt->pal_id,
				mt->repeat,b->t);
			sprintf(path,"%s/%s-%s.ppm",_path,t->name,p->name);
			FILE *g=fopen(path,"w");
			fprintf(g,"P6\n%d\n%d\n255\n",w,h);
			for(uint16 ay=0;ay<h;ay++)
				for(uint16 ax=0;ax<w;ax++)
					fwrite(pixel+(ax+ay*w),3,1,g);
			fclose(g);

		}
		fclose(f);
	}

	return 1;
}

int export_trx(trx *r, char *path){

}
